﻿using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using DevExpress.LookAndFeel;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using TIMA;
using TIMA.DevTeam;

namespace Extensions
{
    public static class GridViewExtensions
    {
        public static Image notready = null;////TODO: Resources.kumasyok4;  //notready5;

        public static void Init(this GridView gridview, BindingSource bs, bool initialized = false)
        {
            try
            {
                gridview.BeginUpdate();
                gridview.Columns.Clear();
                gridview.ViewCaption = gridview.Name;

                gridview.GridControl.DataSource = null;
                gridview.GridControl.DataSource = bs;
                gridview.PopulateColumns();

                foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridview.Columns)
                    if (col.ColumnType == typeof(DateTime))
                    {
                        col.OptionsFilter.FilterPopupMode = FilterPopupMode.DateSmart;
                        col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;
                        col.OptionsFilter.ImmediateUpdateAutoFilter = true;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnCheck = DevExpress.Utils.DefaultBoolean.True;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnDateChange = DevExpress.Utils.DefaultBoolean.True;
                    }

                gridview.OptionsView.EnableAppearanceEvenRow = false;
                gridview.OptionsView.EnableAppearanceOddRow = false;

                gridview.OptionsView.ShowViewCaption = true;
                gridview.BestFitMaxRowCount = 200;
                gridview.GridControl.ShowOnlyPredefinedDetails = true;
                gridview.HorzScrollStep = 50;
                
                gridview.OptionsBehavior.CopyToClipboardWithColumnHeaders = false;
                gridview.OptionsBehavior.ImmediateUpdateRowPosition = false;
                gridview.OptionsBehavior.KeepFocusedRowOnUpdate = true;
                gridview.OptionsFilter.AllowColumnMRUFilterList = true;
                gridview.OptionsFilter.ShowAllTableValuesInCheckedFilterPopup = false;
                gridview.OptionsFilter.ShowAllTableValuesInFilterPopup = false;
                gridview.OptionsHint.ShowColumnHeaderHints = true;
                gridview.OptionsMenu.EnableColumnMenu = true;
                gridview.OptionsMenu.ShowDateTimeGroupIntervalItems = true;
                gridview.OptionsNavigation.UseOfficePageNavigation = true;
                gridview.OptionsSelection.MultiSelect = true;
                gridview.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CellSelect;
                gridview.OptionsView.ColumnAutoWidth = false;
                gridview.OptionsView.RowAutoHeight = true;
                gridview.OptionsView.ShowAutoFilterRow = true;
                gridview.OptionsView.ShowDetailButtons = false;
                gridview.OptionsView.ShowGroupPanel = false;
                gridview.ViewCaption = gridview.ViewCaption.Replace("gv", string.Empty);

                foreach (GridColumn gc in gridview.Columns)
                {
                    string colName = gc.FieldName.ToLower();
                    if (colName == "modifiedon" || colName == "ts" || colName == "deleted")
                        gc.Visible = false;
                    else
                        gc.Visible = true;
                }

            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                gridview.EndUpdate();
            }

            gridview.Appearance.EvenRow.BackColor = (UserLookAndFeel.Default.SkinName == "Office 2007 Black" ? System.Drawing.Color.WhiteSmoke : System.Drawing.Color.FromArgb(250, 245, 245));

            GridManager.GetManager(gridview);
        }

        public static void Init(this GridView gridview, DataTable bs, bool initialized = false)
        {
            try
            {
                gridview.BeginUpdate();
                gridview.Columns.Clear();
                gridview.ViewCaption = gridview.Name;

                gridview.GridControl.DataSource = null;
                gridview.GridControl.DataSource = bs;
                gridview.PopulateColumns();

                foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridview.Columns)
                    if (col.ColumnType == typeof(DateTime))
                    {
                        col.OptionsFilter.FilterPopupMode = FilterPopupMode.DateSmart;
                        col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;
                        col.OptionsFilter.ImmediateUpdateAutoFilter = true;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnCheck = DevExpress.Utils.DefaultBoolean.True;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnDateChange = DevExpress.Utils.DefaultBoolean.True;
                    }

                gridview.OptionsView.EnableAppearanceEvenRow = false;
                gridview.OptionsView.EnableAppearanceOddRow = false;

                gridview.OptionsView.ShowViewCaption = true;
                gridview.BestFitMaxRowCount = 200;
                gridview.GridControl.ShowOnlyPredefinedDetails = true;
                gridview.HorzScrollStep = 50;

                gridview.OptionsBehavior.CopyToClipboardWithColumnHeaders = false;
                gridview.OptionsBehavior.ImmediateUpdateRowPosition = false;
                gridview.OptionsBehavior.KeepFocusedRowOnUpdate = true;
                gridview.OptionsFilter.AllowColumnMRUFilterList = true;
                gridview.OptionsFilter.ShowAllTableValuesInCheckedFilterPopup = false;
                gridview.OptionsFilter.ShowAllTableValuesInFilterPopup = false;
                gridview.OptionsHint.ShowColumnHeaderHints = true;
                gridview.OptionsMenu.EnableColumnMenu = true;
                gridview.OptionsMenu.ShowDateTimeGroupIntervalItems = true;
                gridview.OptionsNavigation.UseOfficePageNavigation = true;
                gridview.OptionsSelection.MultiSelect = true;
                gridview.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CellSelect;
                gridview.OptionsView.ColumnAutoWidth = false;
                gridview.OptionsView.RowAutoHeight = true;
                gridview.OptionsView.ShowAutoFilterRow = true;
                gridview.OptionsView.ShowDetailButtons = false;
                gridview.OptionsView.ShowGroupPanel = false;
                gridview.ViewCaption = gridview.ViewCaption.Replace("gv", string.Empty);

                if (gridview.Columns["Thumbnail"] != null)
                {
                    GridColumn colPhoto = gridview.Columns["Thumbnail"];

                    colPhoto.ColumnEdit = new RepositoryItemPictureEdit();
                    colPhoto.UnboundType = DevExpress.Data.UnboundColumnType.Object;

                    (colPhoto.ColumnEdit as RepositoryItemPictureEdit).SizeMode = PictureSizeMode.Clip;
                    (colPhoto.ColumnEdit as RepositoryItemPictureEdit).NullText = " ";

                    colPhoto.AppearanceCell.Options.UseTextOptions = true;
                    colPhoto.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                     

                    //////gridview.CustomUnboundColumnData -= new DevExpress.XtraGrid.Views.Base.CustomColumnDataEventHandler(gvProduct_CustomUnboundColumnData);
                    //////gridview.RowCellClick -= new RowCellClickEventHandler(gridview_RowCellClick);
                    //////gridview.MouseMove -= new MouseEventHandler(gridview_MouseMove);

                    //////gridview.CustomUnboundColumnData += new DevExpress.XtraGrid.Views.Base.CustomColumnDataEventHandler(gvProduct_CustomUnboundColumnData);
                    //////gridview.RowCellClick += new RowCellClickEventHandler(gridview_RowCellClick);
                    //////gridview.MouseMove += new MouseEventHandler(gridview_MouseMove);


                    gridview.CalcRowHeight -= new RowHeightEventHandler(gridview_CalcRowHeight);
                    gridview.CustomDrawCell -= new DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventHandler(XForm_CustomDrawCell);

                    gridview.CalcRowHeight += new RowHeightEventHandler(gridview_CalcRowHeight);
                    gridview.CustomDrawCell += new DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventHandler(XForm_CustomDrawCell);

                }

                foreach (GridColumn gc in gridview.Columns)
                {
                    string colName = gc.FieldName.ToLower();
                    if (colName == "modifiedon" || colName == "ts" || colName == "deleted")
                        gc.Visible = false;
                    else
                        gc.Visible = true;
                }

                GridManager.GetManager(gridview);

            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                gridview.EndUpdate();
            }

            gridview.Appearance.EvenRow.BackColor = (UserLookAndFeel.Default.SkinName == "Office 2007 Black" ? System.Drawing.Color.WhiteSmoke : System.Drawing.Color.FromArgb(250, 245, 245));
        }


        public static void gridview_CalcRowHeight(object sender, RowHeightEventArgs e)
        {
             
        }

        public static void XForm_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.RowHandle > -1)
                if ((e.Column.FieldName == "Thumbnail" || e.Column.FieldName == "Photo") &&
                    (e.CellValue == DBNull.Value || e.CellValue == null))
                {
                    //e.DisplayText = "X";
                    e.Graphics.DrawImageUnscaled(notready, e.Bounds.X + (e.Bounds.Width / 2 - 16), e.Bounds.Y);
                    e.Handled = true;
                }
        }

        public static void AddSummary(this GridView gridView, params string[] columnNames)
        {
            gridView.OptionsView.ShowFooter = true;
            foreach (GridColumn col in gridView.Columns)
                if (col.Visible == true)
                {
                    col.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
                    col.SummaryItem.DisplayFormat = "{0:#,##0} records";
                    break;
                }

            foreach (string columnName in columnNames)
            {
                GridColumn gc = gridView.Columns[columnName];

                gc.SummaryItem.FieldName = columnName;
                gc.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                gc.SummaryItem.DisplayFormat = "{0:#,##0.#}";
            }
        }

        public static void SetVisibleIndex(this GridView gridView, params string[] orderedColumnNames)
        {
            foreach (GridColumn gc in gridView.Columns)
                gc.Visible = false;

            int index = 0;
            foreach (string col in orderedColumnNames)
            {
                GridColumn gc = gridView.Columns[col];
                //gc.Visible = true;
                gc.VisibleIndex = index++;
            }
        }

        public static void SetCaptions(this GridView gridView, params string[] pairs)
        {
            string problematicCols = string.Empty;
            foreach (string pair in pairs)
            {
                try
                {
                    string[] vals = pair.Split(':');
                    string colName = vals[0].Trim();
                    string caption = vals[1].Trim();
                    gridView.Columns[colName].Caption = caption;
                }
                catch
                {
                    problematicCols += pair + ",";
                }
            }
             
        }

        public static void EndEditing(this GridView gridView)
        {
            gridView.CloseEditor();
            gridView.UpdateCurrentRow();
        }

        public static void MakeColumnsReadOnly(this GridView gridView, params string[] columnNames)
        {
            foreach (string columnName in columnNames)
                gridView.Columns[columnName].OptionsColumn.AllowEdit = false;
        }

        public static void MakeReadOnly(this GridView gridView, params string[] ExceptTheseColumns)
        {
            foreach (GridColumn gc in gridView.Columns)
                gc.OptionsColumn.AllowEdit = ExceptTheseColumns.Any(gc.FieldName.Contains);

            //gridView.OptionsBehavior.Editable = false;
        }

        public static void MakeEditable(this GridView gridView, params string[] ExceptTheseColumns)
        {
            foreach (GridColumn gc in gridView.Columns)
                gc.OptionsColumn.AllowEdit = !ExceptTheseColumns.Any(gc.FieldName.Contains);

            //gridView.OptionsBehavior.Editable = true;
        }


        public static void MakeColumnVisibleWithCaptions(this GridView gridView, params string[] pairs)
        {
            int i = -1;
            foreach (string pair in pairs)
            {
                i++;
                string[] names = pair.Split(':');
                string colName = names[0];
                string caption = names[1];
                gridView.Columns[colName].VisibleIndex = i;
                gridView.Columns[colName].Caption = caption;
            }
        }

        public static void MakeColumnInvisible(this GridView gridView, params string[] columnNames)
        {
            string problematicCols = string.Empty;
            if (columnNames.Length == 0)
            {
                foreach (GridColumn gc in gridView.Columns)
                    gc.Visible = false;
            }
            else
            {
                foreach (string columnName in columnNames)
                {
                    try
                    {
                        gridView.Columns[columnName].Visible = false;
                    }
                    catch
                    {
                        problematicCols += columnName + ",";
                    }
                }
            }
        }

        public static void FormatAsNumber(this GridView gridView,params string[] columnNames)
        {
            string problematicCols = string.Empty;

            foreach (string columnName in columnNames)
            {
                try
                {
                    GridColumn col = gridView.Columns[columnName];
                    col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                    string format = "#,###.";
                    for (int i = 0; i < 2; i++)
                        format += "0";

                    if (format.EndsWith("."))
                        format = format.Substring(0, format.Length - 1);
                    col.DisplayFormat.FormatString = format + ";-" + format + "; ";

                    col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;
                }
                catch
                {
                    problematicCols += columnName + ",";
                }
            }
        }

        public static void MakeRowSelectable(this GridView gridView)
        {
            gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
            gridView.OptionsSelection.EnableAppearanceFocusedRow = true;
            gridView.OptionsSelection.MultiSelect = false;
        }

        public static void VeriyiGuncelle(this GridView gridView, DataTable dt)
        {
            VeriyiGuncelle(gridView, true, dt);
        }

        public static void VeriyiGuncelle(this GridView gridView, bool ClearOldData, DataTable dt)
        {
            DataSet dsRoot = gridView.Dataset();
            if (ClearOldData)
                dsRoot.Tables[dt.TableName].Clear();
            dsRoot.Merge(dt);
            //gridView.BestFitColumns();
        }

        public static void VeriyiGuncelle(this GridView gridView, string SPName, params object[] SPParams)
        {
            VeriyiGuncelle(gridView, true, SPName, SPParams);
        }

        public static void VeriyiGuncelle(this GridView gridView, bool ClearOldData, string SPName, params object[] SPParams)
        {
            DataSet dsRoot = gridView.Dataset();
            if (ClearOldData)
                dsRoot.Clear();

            DataSet dsNew = Data.DM.ExecuteDataSet(SPName, SPParams);

            dsRoot.Merge(dsNew);
            //gridView.BestFitColumns();
        }

        public static DataSet Dataset(this GridView gvMaster)
        {
            DataSet dsRoot = null;
            BindingSource bsRoot = (BindingSource)gvMaster.DataSource;

            int dtSourceIndex = -1;
            while (true)
            {
                dtSourceIndex++;
                if (dtSourceIndex > 10)
                {
                    //Pratikte 10 grid birbirine bağlanmış olmamalıdır ;
                    throw new ApplicationException("Binding kullanım hatası !!!");
                }
                if (bsRoot.DataSource.GetType() == typeof(DataSet))
                {
                    dsRoot = (DataSet)bsRoot.DataSource;
                    return dsRoot;
                }
                else
                {
                    bsRoot = (BindingSource)bsRoot.DataSource;
                }
            }
        }

    }
}